import { useState } from 'react';
import { Modal, Form, Input, Checkbox, Button, message } from 'antd';
import { uid } from '@inbiz/shared';
import SiteTypeComponent from './SiteTypeComponent';
import { langEnum, formatSiteTypeToArray, formatQueryFormData } from '../utils';
import { createLanguages, editLanguages, editFormLang } from '../service';
import '../style.less';
const { confirm } = Modal;

export default function AddOrEditLangModal(props: any) {
    const { visible, setVisible, setEditData, allLangs, editData, queryTableRef, queryBarRef, isForm, selectedRow } = props;
    const [loading, setLoading] = useState(false);
    const [form] = Form.useForm();

    const onCancel = () => {
        setVisible(false);
        setEditData(null);
    };

    const onAddOrEditLang = async () => {
        const formData = await form.validateFields();
        const _formData = { ...formData };
        delete _formData.key;
        delete _formData.SiteType;
        const _kindItems: any[] = []
        for (const key in _formData) {
            const _kindName = langEnum?.find((item) => item?.code == key)?.name;
            _kindItems?.push({
                kindCode: key,
                kindName: _kindName,
                langText: _formData[key],
            });
        };
        const params = isForm ? {
            key: formData?.key,
            kindItems: _kindItems,
            formOutId: selectedRow?.OutId || '',
        } : {
            key: formData?.key,
            siteType: formData.SiteType.reduce((pre: number, cur: number) => pre + cur),
            kindItems: _kindItems,
        };
        setLoading(true);
        try {
            const result = await (editData ? isForm ? editFormLang : editLanguages : createLanguages)(params);
            setLoading(false);
            if (result) {
                if (editData) {
                    queryTableRef?.current?.opCallback && queryTableRef?.current?.opCallback();
                } else {
                    queryTableRef?.current?.opCallbackAfterAdd && queryTableRef?.current?.opCallbackAfterAdd();
                    queryBarRef?.current?.queryForm?.resetFields();
                };
                message.success(editData ? '修改成功' : '新增成功');
                onCancel();
            };
        } catch (error: any) {
            message.error(error);
            setLoading(false);
        };
    };

    const onOk = () => {
        form.validateFields().then((res) => {
            if (editData) {
                confirm({
                    title: '确定要修改此多语言吗？',
                    content: '修改后其他绑定此多语言的组件会同步更新',
                    onOk: () => {
                        onAddOrEditLang();
                    },
                });
            } else {
                onAddOrEditLang();
            };
        });
    };

    return (
        <Modal
            title={editData ? '编辑多语言' : '新建多语言'}
            visible={visible}
            onCancel={onCancel}
            width={500}
            className='inbiz-lang-add-or-edit-modal'
            bodyStyle={{
                maxHeight: document.body.clientHeight * 0.8,
                overflowY: 'auto',
            }}
            footer={[
                <Button key='cancel' onClick={onCancel}>
                    取消
                </Button>,
                <Button
                    loading={loading}
                    key='ok'
                    type='primary'
                    onClick={onOk}
                >
                    确定
                </Button>,
            ]}
        >
            <Form
                form={form}
                name='addOrEditLang'
                labelCol={{ span: 6 }}
                wrapperCol={{ span: 16 }}
                initialValues={
                    isForm ? {
                        key: editData?.Key || `i18n-${uid(8)}`,
                        ...editData,
                    } : {
                        key: editData?.Key || `i18n-${uid(8)}`,
                        ...editData,
                        SiteType: editData?.SiteType ? formatSiteTypeToArray(editData?.SiteType) : [1],
                    }
                }
            >
                {
                    !isForm
                    &&
                    <Form.Item
                        label='所属'
                        name='SiteType'
                        required
                    >
                        <SiteTypeComponent />
                    </Form.Item>
                }
                <Form.Item
                    label='唯一标识'
                    name='key'
                >
                    <Input disabled={true} />
                </Form.Item>
                {
                    allLangs?.map((item: { Code: string; Name: string }) => {
                        return (
                            <Form.Item
                                key={item?.Code}
                                label={item?.Name}
                                name={item?.Code}
                                rules={[
                                    { required: true, message: `请输入${item?.Name}` },
                                    { pattern: /^\S(.*\S)?$/, message: `首尾不能输入空格` },
                                ]}
                            >
                                <Input />
                            </Form.Item>
                        )
                    })
                }
            </Form>
        </Modal>
    )
};